package com.ss.android.article.common;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.SparseBooleanArray;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.controller.AbstractDraweeControllerBuilder;
import com.facebook.drawee.interfaces.SettableDraweeHierarchy;
import com.ss.android.article.base.feature.detail2.event.ThumbPreviewStatusEvent;
import com.ss.android.article.browser.R;
import com.ss.android.common.app.AbsActivity;
import com.ss.android.common.util.ImmersedStatusBarHelper;
import com.ss.android.image.AsyncImageView;
import com.ss.android.image.BaseImageManager;
import com.ss.android.image.DraweeImageViewTouch;
import com.ss.android.image.FrescoUtils;
import com.ss.android.image.Image;
import com.ss.android.image.a.a.TTDraweeControllerBuilder;
import com.ss.android.messagebus.SubscriptionRouter;
import com.ss.android.newmedia.activity.BaseActivity;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

public class ThumbPreviewActivity extends AbsActivity {
    public final class ScreenShotAdapter extends PagerAdapter {

        public final int getCount() {
            return mLargeImages.size();
        }

        public final Object instantiateItem(ViewGroup container, final int position) {
            final ViewHolder viewHolder = new ViewHolder(ThumbPreviewActivity.this, android.support.design.a.b(container, R.layout.image_preview_item));
            Image largeImage = mLargeImages.get(position);
            Image smallImage = mSmallImages == null || position >= mSmallImages.size() ? null : mSmallImages.get(position);
            int largeImageHeight = largeImage.height;
            int largeImageWidth = largeImage.width;
            float v3_1 = (float) largeImageWidth == 0f ? 0f : (float) largeImageHeight / (float) largeImageWidth;
            float v5_1 = mScreenWidth == 0 ? 0f : (((float) mScreenHeight)) / (((float) mScreenWidth));
            if (v5_1 == 0f) {
                viewHolder.mImage.setFitToScreen(true);
            } else if (v3_1 / v5_1 > 2f) {
                viewHolder.mImage.setFitToWidth(true);
            } else {
                viewHolder.mImage.setFitToScreen(true);
            }

            if (largeImage.width > 2048 || largeImage.height > 2048) {
                viewHolder.mImage.setLayerType(1, null);
            } else {
                viewHolder.mImage.setLayerType(2, null);
            }

            if (mThumbWidth > 0 && mThumbHeight > 0) {
                ViewGroup.LayoutParams layoutParams = viewHolder.mThumbImage.getLayoutParams();
                layoutParams.width = mThumbWidth;
                layoutParams.height = mThumbHeight;
            }

            if (smallImage != null) {
                viewHolder.mThumbImage.setImage(((Image) smallImage));
                viewHolder.mThumbImage.setVisibility(View.VISIBLE);
            } else {
                viewHolder.mThumbImage.setVisibility(View.INVISIBLE);
            }

            viewHolder.mImage.setVisibility(View.INVISIBLE);
            viewHolder.mLoadingProgress.setVisibility(View.VISIBLE);
            AbstractDraweeControllerBuilder abstractDraweeControllerBuilder = android.support.design.a.sTTDraweeControllerBuilderSupplier.get()
                    .setAutoPlayAnimations()
                    .setFirstAvailableImageRequests(FrescoUtils.buildImageRequests(largeImage));
            if (viewHolder.mImage.getController() != null) {
                abstractDraweeControllerBuilder.setOldController(viewHolder.mImage.getController());
            }
            viewHolder.mImage.setHierarchy(new SettableDraweeHierarchy() {


                public final Drawable getTopLevelDrawable() {
                    return getResources().getDrawable(com.ss.android.article.browser.R.color.bg_place_holder);
                }

                public final void setImage(Drawable drawable, float progress, boolean immediate) {
                    int v2 = View.GONE;
                    if (drawable == null) {
                        this.setFailure();
                    } else if (progress >= 1f) {
                        viewHolder.mImage.setImageDrawable(drawable);
                        viewHolder.mImage.setVisibility(View.VISIBLE);
                        viewHolder.mThumbImage.setVisibility(v2);
                        viewHolder.mLoadingProgress.setVisibility(v2);
                        mImageLoadedSuccess.put(position, true);
                        updateFooterView(position);
                    }
                }

                public final void reset() {
                    viewHolder.mImage.setImageDrawable(null);
                }

                public final void setProgress() {
                }

                public final void setFailure() {
                    viewHolder.mImage.setVisibility(View.INVISIBLE);
                    viewHolder.mLoadingProgress.setVisibility(View.GONE);
                    mImageLoadedSuccess.put(position, false);
                    updateFooterView(position);
                    Toast.makeText(ThumbPreviewActivity.this, R.string.loading_failed, Toast.LENGTH_SHORT).show();
                }

                public final void setRetry() {
                }

                public final void setControllerOverlay() {
                }
            });
            viewHolder.mImage.setController(((TTDraweeControllerBuilder) abstractDraweeControllerBuilder).buildController());
            container.addView(viewHolder.mItemView);
            return viewHolder;
        }

        public final void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(((ViewHolder) object).mItemView);
        }

        public final boolean isViewFromObject(View view, Object object) {
            return view == ((ViewHolder) object).mItemView;
        }
    }

    static final class ViewHolder {
        public final ThumbPreviewActivity e;
        View mItemView;
        DraweeImageViewTouch mImage;
        AsyncImageView mThumbImage;
        ProgressBar mLoadingProgress;
        private View.OnClickListener mCloseClickListener;

        ViewHolder(ThumbPreviewActivity arg3, View view) {
            this.e = arg3;
            this.mCloseClickListener = new View.OnClickListener() {

                public final void onClick(View view) {
                    ViewHolder.this.e.finish();
                }
            };
            this.mItemView = view;
            this.mImage = view.findViewById(com.ss.android.article.browser.R.id.image);
            this.mThumbImage = view.findViewById(com.ss.android.article.browser.R.id.thumb_image);
            this.mLoadingProgress = view.findViewById(com.ss.android.article.browser.R.id.loading_progress);
            this.mItemView.setOnClickListener(this.mCloseClickListener);
            this.mImage.setMyOnClickListener(this.mCloseClickListener);
        }
    }

    List<Image> mSmallImages;
    List<Image> mLargeImages;
    int mThumbWidth;
    int mThumbHeight;
    BaseImageManager mImageMgr;
    int mScreenWidth;
    int mScreenHeight;
    SparseBooleanArray mImageLoadedSuccess;
    int mSelectedIndex;
    private TextView mPageNumber;
    private TextView mSaveTextView;
    private boolean mFirstResume;
    private View.OnClickListener mSaveClickListener;
    private ViewPager.OnPageChangeListener mOnPageChangeListener;
    private ScreenShotAdapter mViewPager;
    private DataSetObserver mDataSetObserver;

    public ThumbPreviewActivity() {
        this.mFirstResume = true;
        this.mSaveClickListener = new View.OnClickListener() {

            public final void onClick(View arg5) {
                if (mLargeImages != null && mLargeImages.size() > 0) {
                    Image image = mLargeImages.get(((Integer) arg5.getTag()).intValue());
                    if (image != null && !image.isLocal()) {
                        String url = image.url;
                        if (!android.support.design.a.isTextEmpty(url)) {
                            mImageMgr.b(ThumbPreviewActivity.this, com.bytedance.common.utility.aa.md5(url), url);
                        }
                    }
                }
            }
        };
        this.mOnPageChangeListener = new ViewPager.OnPageChangeListener() {

            public final void onPageScrollStateChanged(int state) {
            }

            public final void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            public final void onPageSelected(int position) {
                mSelectedIndex = position;
                ThumbPreviewActivity.this.updateFooterView(position);
            }
        };
        this.mDataSetObserver = new DataSetObserver() {

            public final void onChanged() {
                super.onChanged();
                ThumbPreviewActivity.this.updateFooterView(ThumbPreviewActivity.this.mSelectedIndex);
            }
        };
    }

    public static void startActivity(Context context, List<Image> largeImages, int selectedIndex) {
        Intent intent = new Intent(context, ThumbPreviewActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("large_images", (Serializable) largeImages);
        bundle.putInt("selected_index", selectedIndex);
        intent.putExtras(bundle);
        context.startActivity(intent);
        if ((context instanceof BaseActivity)) {
            ((BaseActivity) context).superOverridePendingTransition(R.anim.thumb_fade_in, R.anim.thumb_fade_out_fake);
        } else if ((context instanceof Activity)) {
            ((Activity) context).overridePendingTransition(R.anim.thumb_fade_in, R.anim.thumb_fade_out_fake);
        }
    }

    public static void startActivity(ImageView imageView, List<Image> smallImages, List<Image> largeImages, int selectedIndex) {
        Intent intent = new Intent(imageView.getContext(), ThumbPreviewActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("large_images", ((Serializable) largeImages));
        bundle.putSerializable("small_images", ((Serializable) smallImages));
        bundle.putInt("thumb_width", imageView.getWidth());
        bundle.putInt("thumb_height", imageView.getHeight());
        bundle.putInt("selected_index", selectedIndex);
        intent.putExtras(bundle);
        Context context = imageView.getContext();
        context.startActivity(intent);
        if ((context instanceof BaseActivity)) {
            ((BaseActivity) context).superOverridePendingTransition(R.anim.thumb_fade_in, R.anim.thumb_fade_out_fake);
        } else if ((context instanceof Activity)) {
            ((Activity) context).overridePendingTransition(R.anim.thumb_fade_in, R.anim.thumb_fade_out_fake);
        }
    }

    final void updateFooterView(int currentPosition) {
        if (this.mSelectedIndex == currentPosition) {
            this.mPageNumber.setText(String.format("%d/%d", Integer.valueOf(currentPosition + 1), Integer.valueOf(this.mLargeImages.size())));
            this.mSaveTextView.setTag(Integer.valueOf(currentPosition));
            this.mSaveTextView.setEnabled(this.mImageLoadedSuccess.get(currentPosition));
        }
    }

    public void finish() {
        super.finish();
        this.overridePendingTransition(0, R.anim.thumb_fade_out);
    }

    public ImmersedStatusBarHelper.ImmersedStatusBarConfig getImmersedStatusBarConfig() {
        return new ImmersedStatusBarHelper.ImmersedStatusBarConfig().setStatusBarColor(com.ss.android.article.browser.R.color.status_bar_color_black);
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.image_preview_view);
        this.mImageMgr = new BaseImageManager(this);
        this.mImageLoadedSuccess = new SparseBooleanArray();
        this.mPageNumber = (TextView) this.findViewById(R.id.page_number);
        this.mSaveTextView = (TextView) this.findViewById(R.id.save_textview);
        Display display = this.getWindowManager().getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        this.mScreenWidth = metrics.widthPixels;
        this.mScreenHeight = metrics.heightPixels;
        Intent intent = this.getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                this.mLargeImages = (List) bundle.getSerializable("large_images");
                this.mSmallImages = (List) bundle.getSerializable("small_images");
                this.mThumbWidth = bundle.getInt("thumb_width");
                this.mThumbHeight = bundle.getInt("thumb_height");
                this.mSelectedIndex = intent.getIntExtra("selected_index", 0);
                if (!android.support.design.a.isEmptyCollection((Collection) this.mLargeImages)) {
                    ViewPager mViewPager = (ViewPager) this.findViewById(R.id.screenshot_gallery);
                    this.mViewPager = new ScreenShotAdapter();
                    this.mViewPager.registerDataSetObserver(this.mDataSetObserver);
                    mViewPager.setAdapter(this.mViewPager);
                    mViewPager.setOnPageChangeListener(this.mOnPageChangeListener);
                    mViewPager.setCurrentItem(this.mSelectedIndex);
                    this.updateFooterView(this.mSelectedIndex);
                    this.mSaveTextView.setOnClickListener(this.mSaveClickListener);
                } else {
                    this.finish();
                }
            } else {
                this.finish();
            }
        } else {
            this.finish();
        }
    }

    public void onDestroy() {
        super.onDestroy();
        if (this.mViewPager != null) {
            this.mViewPager.unregisterDataSetObserver(this.mDataSetObserver);
        }
    }

    public void onPause() {
        super.onPause();
        if (!this.isFinishing()) {
            SubscriptionRouter.c(new ThumbPreviewStatusEvent(1));
        }
    }

    public void onResume() {
        super.onResume();
        if (this.mFirstResume) {
            this.mFirstResume = false;
        } else {
            SubscriptionRouter.c(new ThumbPreviewStatusEvent(0));
        }
    }
}

